//
//  BlueAccompanyViewController.m
//  leo
//
//  Created by 张旭 on 15/12/18.
//  Copyright © 2015年 mdx. All rights reserved.
//

#import "BlueAccompanyViewController.h"

@interface BlueAccompanyViewController ()
@property (nonatomic, strong) UIImage *mAvatarImage;
@property (nonatomic, retain) NSString *mStatusLabelValue;
@property (nonatomic, retain) NSString *mMacAddress;
@property (nonatomic, retain) NSString *mUserID;
@property(nonatomic,retain) AppDelegate *mydelegate;
@property (nonatomic,assign) BOOL isAlreadyUnreg;

@property (nonatomic, strong)UIImageView *bgImageView;
@property (nonatomic, strong)UIImageView *scanningImageView;
@end

@implementation BlueAccompanyViewController
@synthesize avatarImage;
@synthesize avatarImageView;
@synthesize statusLabelValue;
@synthesize macAddress;
@synthesize userID;
@synthesize isStartByDisConnectNoti;
@synthesize isNeedReconnect;
@synthesize hideOrReconnectButton;
-(void)onDeviceDisconnected:(NSObject *)cookie macAddress:(NSString *)macAddress {
    //TODO
    if ([(NSString*)cookie isEqual:@"CONNECTED"]) {
        self.statusLabel.text = [NSString stringWithFormat:@"%@ 已断开",self.mStatusLabelValue];
    }else{
        self.statusLabel.text = [NSString stringWithFormat:@"%@ 长连接失败请重连",self.mStatusLabelValue];
    }
    self.mydelegate.isBLEUnderConnect = NO;
    [self.hideOrReconnectButton setHidden:NO];
    [self.hideOrReconnectButton setTitle:@"重连" forState:UIControlStateNormal];
    [self.hideOrReconnectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFYBLEDEVICEDISCONNECTED object:nil  userInfo:nil];
    
    self.backImgView.image = [UIImage imageNamed:@"blueaccompany_bg1"];
       [_scanningImageView removeFromSuperview];
    _avtarTopConstraint.priority = 751;
    _avatarCenterConstraint.priority = 750;
     _statusTopConstraint.constant = -110;
   
     [self.view layoutIfNeeded];

}

-(void)onDeviceConnected:(NSObject *)cookie macAddress:(NSString *)macAddress {
    [self.hideOrReconnectButton setHidden:NO];
    [self.hideOrReconnectButton setTitle:@"隐藏" forState:UIControlStateNormal];
    [self.hideOrReconnectButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.mydelegate.isBLEUnderConnect = YES;
    self.statusLabel.text = [NSString stringWithFormat:@"%@ 随行中",self.mStatusLabelValue];
    self.backImgView.image = [UIImage imageNamed:@"blueaccompany_bg1"];
       [_scanningImageView removeFromSuperview];
    _avtarTopConstraint.priority = 751;
    _avatarCenterConstraint.priority = 750;
        _statusTopConstraint.constant = -110;
     [self.view layoutIfNeeded];

}

-(UIImage *)avatarImage{
    return self.mAvatarImage;
}

-(void)setAvatarImage:(UIImage *)avatar
{
    self.mAvatarImage = avatar;
}

-(NSString *)statusLabelValue{
    return self.mStatusLabelValue;
}

-(void)setStatusLabelValue:(NSString *)value{
    self.mStatusLabelValue = value;
}

-(NSString *)macAddress
{
    return self.mMacAddress;
}

-(void)setMacAddress:(NSString *)value
{
    self.mMacAddress = value;
}

-(NSString *)userID{
    return self.mUserID;
}

-(void)setUserID:(NSString *)value{
    self.mUserID = value;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self renderAvatarView];
    [self renderButtonView];
    [self initButtonStatus];
    [self.avatarImageView setImage:self.mAvatarImage];
    self.mydelegate=[[UIApplication sharedApplication] delegate];

    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidAppear:(BOOL)animated{
    self.isAlreadyUnreg = NO;
    [self registObservers];
    if (self.mydelegate.isBLEUnderConnect) {
        [self.hideOrReconnectButton setHidden:NO];
        [self.hideOrReconnectButton setTitle:@"隐藏" forState:UIControlStateNormal];
        self.statusLabel.text = [NSString stringWithFormat:@"%@ 随行中",self.mStatusLabelValue];
        self.backImgView.image = [UIImage imageNamed:@"blueaccompany_bg1"];
           [_scanningImageView removeFromSuperview];
        _avtarTopConstraint.priority = 751;
        _avatarCenterConstraint.priority = 750;
            _statusTopConstraint.constant = -110;
         [self.view layoutIfNeeded];

    }
    else if (!self.isStartByDisConnectNoti) {
        self.statusLabel.text = [NSString stringWithFormat:@"正在连接 %@",self.mStatusLabelValue];
        [self scanAnimate];
        [[BleManager getInstance:YES]registerConnectionListener:(ConnectionListener *)self macAddress:self.mMacAddress userID:self.userID withCookie:nil];
    }else{
        self.statusLabel.text = [NSString stringWithFormat:@"%@ 已断开",self.mStatusLabelValue];
        [[BleManager getInstance:YES]unregisterConnectionListener:self.mMacAddress];
        [self.hideOrReconnectButton setHidden:NO];
        [self.hideOrReconnectButton setTitle:@"重连" forState:UIControlStateNormal];
        self.backImgView.image = [UIImage imageNamed:@"blueaccompany_bg1"];
        [_scanningImageView removeFromSuperview];
        _avtarTopConstraint.priority = 751;
        _avatarCenterConstraint.priority = 750;
            _statusTopConstraint.constant = -110;
       [self.view layoutIfNeeded];

    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [self removeObservers];
}

-(void)renderAvatarView
{
    [self.avatarImageView.layer setMasksToBounds:YES];
    self.avatarImageView.layer.cornerRadius=self.avatarImageView.bounds.size.width/2;
    self.avatarImageView.clipsToBounds=YES;
}


-(void)renderButtonView
{
    for (int i = 0; i < self.buttonsCollections.count; i++) {
        UIButton* button = [self.buttonsCollections objectAtIndex:i];
        [button.layer setCornerRadius:8];
        [button.layer setBorderWidth:1];
        [button.layer setBorderColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor];
    }
    [self.cancelButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.hideOrReconnectButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)initButtonStatus{
    [self.hideOrReconnectButton setHidden:YES];
}

-(void)buttonAction:(id)sender
{
    if (sender == self.cancelButton) {
        if (!self.isAlreadyUnreg) {
           [[BleManager getInstance:YES]unregisterConnectionListener:self.mMacAddress];
        }
        self.mydelegate.isBLEUnderConnect = NO;
        [self dismissViewControllerAnimated:YES completion:nil];
    }else if(sender == self.hideOrReconnectButton){
        if(isStartByDisConnectNoti||isNeedReconnect){
            self.statusLabel.text = [NSString stringWithFormat:@"正在连接 %@",self.mStatusLabelValue];
            [[BleManager getInstance:YES]registerConnectionListener:(ConnectionListener *)self macAddress:self.mMacAddress userID:self.userID withCookie:nil];
            isStartByDisConnectNoti = NO;
            [self.hideOrReconnectButton setHidden:YES];
            [self scanAnimate];
        }else{
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)registObservers{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:NOTIFYBLEDEVICEDISCONNECTED object:nil];
}

- (void)removeObservers{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFYBLEDEVICEDISCONNECTED object:nil];
}

- (void)receiveNotification:(NSNotification *)sender{
    NSLog(@"BLEVC : receiveNotification = %@",sender.name);
    if ([sender.name isEqualToString:NOTIFYBLEDEVICEDISCONNECTED]) {
        //TODO do what?
        [[BleManager getInstance:YES]unregisterConnectionListener:self.mMacAddress];
        self.isAlreadyUnreg = YES;
        self.statusLabel.text = [NSString stringWithFormat:@"%@ 已断开",self.mStatusLabelValue];
        //[self.hideOrReconnectButton setHidden:NO];
        [self.hideOrReconnectButton setTitle:@"重连" forState:UIControlStateNormal];
        self.isNeedReconnect = YES;
    }
}


//UI更改
- (void)scanAnimate
{

    
    _avtarTopConstraint.priority = 751;
    _avatarCenterConstraint.priority = 752;
    _statusTopConstraint.constant = 60;
    [self.view layoutIfNeeded];
    self.backImgView.image = [UIImage imageNamed:@"bleBackGray"];
    
    UIImage *scanningImage = [UIImage imageNamed:@"scan"];
    
    _scanningImageView = [UIImageView new];
    _scanningImageView.frame = CGRectMake(0, 0, 512, 512);
    _scanningImageView.center = self.view.center;
    
    _scanningImageView.image = scanningImage;
    
    
    [self.backImgView addSubview:_scanningImageView];
    
    CABasicAnimation *scannigAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    
    //    angle：旋转的弧度，所以要把角度转换成弧度：角度 * M_PI / 180。
    CATransform3D transform = CATransform3DMakeRotation(90*M_PI/180, 0, 0, 1);//顺时针旋转
    transform.m34 = 0.05;// 透视效果
    //    transform.autoreverses = YES;
    
    NSValue *value = [NSValue valueWithCATransform3D:transform];
    [scannigAnimation setToValue:value];
    
    scannigAnimation.autoreverses = NO;//原路返回动画一遍
    scannigAnimation.duration = 2.0;
    scannigAnimation.repeatCount = HUGE_VALF;
    //basicAnimation.repeatCount=HUGE_VALF;//设置重复次数,HUGE_VALF可看做无穷大，起到循环动画的效果
    //    basicAnimation.removedOnCompletion=NO;//运行一次是否移除动画
    
    scannigAnimation.fillMode = kCAFillModeBackwards;
    
    scannigAnimation.cumulative = YES;
    
    scannigAnimation.removedOnCompletion = NO;
    
    scannigAnimation.delegate = self;
    
    [_scanningImageView.layer addAnimation:scannigAnimation forKey:nil];

}
#pragma mark - 动画代理方法
#pragma mark 动画开始
-(void)animationDidStart:(CAAnimation *)anim{
    //    NSLog(@"animation(%@) start.\r_layer.frame=%@",anim,NSStringFromCGRect(_layer.frame));
    //    NSLog(@"%@",[_layer animationForKey:@"KCBasicAnimation_Translation"]);//通过前面的设置的key获得动画
    NSLog(@"%s", __func__);
}
#pragma mark 动画结束
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    //    NSLog(@"animation(%@) stop.\r_layer.frame=%@",anim,NSStringFromCGRect(_layer.frame));
    //    _layer.position=[[anim valueForKey:@"KCBasicAnimationLocation"] CGPointValue];
    NSLog(@"%s", __func__);
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
